#include "accelerometer.h"
#include "device.h"
#include "display.h"
#include "error.h"
#include "iic.h"
#include "reports.h"
#include "rtc.h"
#include "usb.h"
#include "version.h"

uint	timeOfs;
uint	timer;
uint	curSteps;
uint	systick;
ushort	error;
ushort	flags;
ubyte	status;
ubyte	clrSteps;
REPORTS reports={RPT_VERSION,0,
	RPT_TICKLO,0,	RPT_TICKHI,0,
	RPT_OFFSETLO,0,	RPT_OFFSETHI,0,
	RPT_VOLTB,0,	RPT_VOLTC,0,	RPT_VOLTS,3300,	
	RPT_TKCHGL,0,	RPT_TKCHGH,0,
	RPT_TCCHGC,0,	RPT_TCCHGV,0,
	RPT_PRODUCT,3,	RPT_CONFIG,0,
	RPT_ACCKLO,0,	RPT_ACCKHI,0,
};
SAVE	savRam;
uint	version_vect	=0x08000000;
uint	version_bottom	=0x08008800;

static void testAccelerometer(void){
	accelerometer_init();
	ubyte v;
	iic_read(ADD_ACC,REG_WHOIAM,&v,1);
	iic_wait();
	if(v!=0x33)
		error|=ERROR_ACCSENSOR;
}
static void testRTC(void){
	rtc_init();
	for(timer=0;timer<10000;){
		if(RCC_GetFlagStatus(RCC_FLAG_LSERDY))
			return;
		display_bar(timer/700+3);
	}
	error |= ERROR_RTC;
}

//------------------------------------------------------------------------------

void main(void){
	device_init(1);
	if(SystemCoreClock!=48000000)
		error |=ERROR_SYSCLK;
	device_watchdog(1);
	device_checkPower();
	if(usb_noPower())
		device_standby();
	device_speed(1);

	display_on();
	display_bar(1);
	usb_on();
	display_bar(2);
	testAccelerometer();
	display_bar(3);
	testRTC();
	display_bar(19);
	while(1){
		if(error)
			display_hex(error);
		else if(usb_noPower())
			PWR_EnterSTANDBYMode();
		else{
			report();
			dispatch();
		}
		__WFI();
	}
}